package com.wondersgroup.insurance.dnuilearn.views.shader;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;

/**
 * Created by Administrator on 2017/5/11.
 */

public class LinearGradientTextView extends AppCompatTextView {
//    private int[] mColors = {Color.RED,Color.GREEN,Color.BLUE,Color.YELLOW};
    LinearGradient linearGradient = null;
        private int[] mColors =   new int[]{0x22ffffff, 0xffffffff, 0x22ffffff};
    private Paint mPaint;

    private float mTranslate;
    private float DELTAX = 20;


    public LinearGradientTextView(Context context) {
        this(context, null);
    }

    public LinearGradientTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LinearGradientTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);


    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        String str = getText().toString();
        float textWidth = getPaint().measureText(str);
        // 3个文字的宽度
        int gradientSize = (int) (textWidth / str.length() * 3);
        linearGradient = new LinearGradient(-gradientSize,0,0,0,mColors,null, Shader.TileMode.CLAMP);

        getPaint().setShader(linearGradient);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mTranslate += DELTAX;
        float textWidth = getPaint().measureText(getText().toString());
        if  (mTranslate +1 > textWidth || mTranslate < 1){
            DELTAX = - DELTAX;
        }
        Matrix matrix = new Matrix();
        matrix.setTranslate(mTranslate,0);
        linearGradient.setLocalMatrix(matrix);

//        canvas.drawRect(0,rect.top,100,rect.height(),mPaint);

        postInvalidateDelayed(50);
    }
}
